package com.taotao.stack;

/**
 * 栈
 *
 * @author Administrator
 * @date 2020/7/13 14:07
 */
public class Stack<T> {

    private static class Node<T> {
        T data;
        Node<T> next;
    }

    private int size;

    private Node<T> head;

    public Stack() {
        size = 0;
        head = new Node<>();
    }


    /**
     * 入栈
     *
     * @param data
     */
    public void push(T data) {
        Node<T> node = new Node();
        node.data = data;

        head.next = node;

    }


    /**
     * 出栈
     *
     * @return
     */
    public T pop() {
        Node<T> top = head.next;
        if (null == top) {
            return null;
        }

        head.next = top.next;

        return top.data;

    }


    /**
     * 取栈顶
     *
     * @return
     */
    public T top() {
        Node<T> top = head.next;
        if (null == top) {
            return null;
        }
        return top.data;
    }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("Stack ");
        Node<T> node = head.next;
        while (null != node) {
            sb.append("->").append(node.data);
        }

        return sb.toString();
    }
}
